package com.freewei.bing;

import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.memetix.mst.detect.Detect;
import com.memetix.mst.language.Language;
import com.memetix.mst.translate.Translate;

import org.json.simple.JSONValue;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private EditText text_id,text_pwd;
    private  boolean isLoading = false;
    private String token = "";
    private List<View> views;

    ViewPager pager;
    private Spinner sp1;
    private Spinner sp2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text_id = (EditText) findViewById(R.id.app_id);
        text_pwd = (EditText) findViewById(R.id.app_pwd);

        views = new ArrayList<>(2);
        views.add(findViewById(R.id.frame1));
        views.add(findViewById(R.id.frame2));
        pager = (ViewPager) findViewById(R.id.viewpager);
        pager.setAdapter(new PagerAdapter() {
            @Override
            public Object instantiateItem(ViewGroup arg0, int arg1) {
                return views.get(arg1);
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return position == 0 ? "Detect" : "Translate";
            }

            @Override
            public void destroyItem(ViewGroup arg0, int arg1, Object arg2) {
                arg0.removeView(views.get(arg1));
            }

            @Override
            public int getCount() {
                return views.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object o) {
                return view == o;
            }

        });

        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    changeModel(findViewById(R.id.change1));
                } else {
                    changeModel(findViewById(R.id.change2));
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        sp1 = ((Spinner) findViewById(R.id.spinner1));
        sp2 = ((Spinner) findViewById(R.id.spinner2));

        List<String> s = new ArrayList<>();
        for (Language l :Language.values()){
            s.add(l.name());
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_dropdown_item_1line, s  );
        sp1.setAdapter(adapter);
        sp2.setAdapter(adapter);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main_activity, menu);
        return true;
    }

    public  void refresh(MenuItem item){
        isLoading = false;
        token = "";
        text_id.setText(getString(R.string.app_id));
        text_pwd.setText(getString(R.string.app_pwd));
        findViewById(R.id.models).setVisibility(View.GONE);
        TextView source = (TextView) findViewById(R.id.detect_source);
        TextView result = (TextView) findViewById(R.id.detect_result);
        source.setText("");
        result.setText("");
         source = (TextView) findViewById(R.id.translate_source);
         result = (TextView) findViewById(R.id.translate_result);
        source.setText("");
        result.setText("");

    }
    public  void look_token(MenuItem item){
        new AlertDialog.Builder(this).setTitle("token").setMessage(
                TextUtils.isEmpty(token)?"current token is null" : "token = " +token)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create().show();
    }


    public  void changeModel(View v){
        switch (v.getId()){
            case R.id.change1:
                v.setBackgroundColor(getResources().getColor(android.R.color.holo_red_light));
                findViewById(R.id.change2).setBackgroundColor(getResources().getColor(android.R.color.white));
                pager.setCurrentItem(0);
                break;

            case R.id.change2:
                v.setBackgroundColor(getResources().getColor(android.R.color.holo_red_light));
                findViewById(R.id.change1).setBackgroundColor(getResources().getColor(android.R.color.white));
                pager.setCurrentItem(1);
                break;
        }
    }

    public void getMyToken(final View v){
        if (isLoading) return;
        new AsyncTask<String,Integer,String>(){
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                isLoading = true;
                findViewById(R.id.pb).setVisibility(View.VISIBLE);
            }

            @Override
            protected String doInBackground(String...params) {
                try {
                    return Translate.getToken(params[0], params[1]);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return "";
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                findViewById(R.id.pb).setVisibility(View.GONE);
                if ("".equals(s)) {
                    Toast.makeText(MainActivity.this,"get token failed...",Toast.LENGTH_LONG).show();
                }else {
                    Toast.makeText(MainActivity.this,"get token success...",Toast.LENGTH_LONG).show();
                }
                token = "Bearer " + (String)((org.json.simple.JSONObject) JSONValue.parse(s)).get("access_token");
                isLoading =false;
                findViewById(R.id.models ).setVisibility(View.VISIBLE);
            }
        }.execute(text_id.getText().toString(),text_pwd.getText().toString());
    }

    public  void  Detect(View v){
        TextView source = (TextView) findViewById(R.id.detect_source);
        final TextView result = (TextView) findViewById(R.id.detect_result);
        new AsyncTask<String,Integer,String>(){

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                result.setText("");
                findViewById(R.id.pb1).setVisibility(View.VISIBLE);
                Detect.setClientId(text_id.getText().toString());
                Detect.setClientSecret(text_pwd.getText().toString());
            }

            @Override
            protected String doInBackground(String... params) {

                try {

                    return  Detect.execute(params[0]).name();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                findViewById(R.id.pb1).setVisibility(View.GONE);
                if (s!=null){
                    result.setText(s);
                }else {
                    Toast.makeText(MainActivity.this,"Detect failed...",Toast.LENGTH_LONG).show();

                }


            }
        }.execute(source.getText().toString());
    }


    public  void  Translate(View v){
        TextView source = (TextView) findViewById(R.id.translate_source);
        final TextView result = (TextView) findViewById(R.id.translate_result);
        new AsyncTask<String,Integer,String>(){

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                result.setText("");
                findViewById(R.id.pb2).setVisibility(View.VISIBLE);
                Translate.setClientId(text_id.getText().toString());
                Translate.setClientSecret(text_pwd.getText().toString());

            }

            @Override
            protected String doInBackground(String... params) {
                try {
                    return  Translate.execute(params[0],
                            Language.valueOf(params[1]), Language.valueOf(params[2]));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                findViewById(R.id.pb2).setVisibility(View.GONE);
                if (s!=null){
                    result.setText(s);
                }else {
                    Toast.makeText(MainActivity.this,"Translate failed...",Toast.LENGTH_LONG).show();

                }


            }
        }.execute(source.getText().toString(), sp1.getSelectedItem().toString(),sp2.getSelectedItem().toString());
    }

}
